package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping//添加分类
    public R<String> save(@RequestBody Category category){
        log.info("category:{}",category);
        categoryService.save(category);
        return R.success(null);

    }
    @GetMapping("/page")//观看分类
    public R<Page> getAll(Integer page,Integer pageSize){
        log.info("page = {},pageSize = {}",page,pageSize);
        //创建分页传入数据
        Page<Category> pages = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        categoryService.page(pages,queryWrapper);
       return R.success(pages);
    }
    @DeleteMapping
    public R<String> deleted(Long id){
        log.info("id:{}",id);
        categoryService.remove(id);
        return R.success("删除成功");
    }

    @PutMapping
    public R<String> updateById(@RequestBody Category category){
        log.info("category:{}",category);
        categoryService.updateById(category);
        return R.success("修改成功");
    }
    @GetMapping("/list")
    public R<List<Category>> listR(Category category){
        LambdaQueryWrapper<Category> categoryWrapper = new LambdaQueryWrapper<>();
        categoryWrapper.eq(category.getType() != null, Category::getType,category.getType());
        categoryWrapper.orderByDesc(Category::getType).orderByAsc(Category::getUpdateTime);
        List<Category> list = categoryService.list(categoryWrapper);
        return R.success(list);
    }

}
